package com.noexcs.forum.controller;

import com.noexcs.forum.entity.DiscussPost;
import com.noexcs.forum.entity.Page;
import com.noexcs.forum.entity.User;
import com.noexcs.forum.service.DiscussPostService;
import com.noexcs.forum.service.UserService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author noexcs
 * @since 5/20/2022 5:47 PM
 */
@Controller
public class HomeController {

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;

    @GetMapping("/")
    public String root() {
        return "forward:/index";
    }

    /**
     *
     * @param model
     * @param page
     * @param orderMode
     * @return
     */
    @GetMapping("/index")
    public String getIndexPage(Model model, Page page,
                               @RequestParam(name = "orderMode", defaultValue = "0") int orderMode) {

        // 方法调用前，SpringMVC会自动实例化Model和Page，并将Page注入Model
        page.setRows(discussPostService.findDiscussPostRows(0));
        page.setPath("/index");

        List<DiscussPost> discussPosts = discussPostService.findDiscussPosts(0, page.getOffset(), page.getLimit());
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        for (DiscussPost post : discussPosts) {
            HashMap<String, Object> postUserMap = new HashMap<>(4);
            postUserMap.put("post", post);
            User user = userService.findUserById(post.getUserId());
            postUserMap.put("user", user);
            list.add(postUserMap);
        }
        model.addAttribute("discussPosts", list);
        return "index";
    }

    @GetMapping(path = "/error")
    public String getErrorPage() {
        return "/error/500";
    }

}
